package zmee.bid.oa;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.openapi.common.result.OpenApiFile;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.FileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import zmee.util.BosUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @author lijiawang
* @Date 2022/12/2 17:16
* @Description:OA回传接口
*/
@ApiController(value = "pur", desc = "OA回传审批记录")
public class DecisionBiddocApi {
    private static Log logger = LogFactory.getLog(DecisionBiddocApi.class);
    @ApiPostMapping("/doFileService")
    public CustomApiResult<String> doCustomService(@ApiParam(value="单据标识", required=true , example="src_biddoc") String sign,
                                                    @ApiParam(value="编码", required=true, example="单据编码") String billno,
                                                    @ApiParam(value="附件名称", required=true, example="xxx.pdf") String attName,
                                                    @ApiParam(value="附件输入流", required=true) OpenApiFile file) {
        CustomApiResult apiResult=new CustomApiResult();
        if(sign == null || billno == null || file == null || attName == null){
            apiResult.setStatus(false);
            apiResult.setErrorCode("参数非法");
        }else{
            logger.info("==oaseriver=="+sign+"===billno==="+billno+"===修改前attName==="+attName+"===accessory==="+file);
            StringBuilder str=new StringBuilder();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            str.append("审批记录-");
            str.append(dateFormat.format(new Date()));
            str.append("-");
            str.append(System.currentTimeMillis());
            str.append(".pdf");
            String name=str.toString();
            logger.info("===修改后attName==="+name);
            byte[] fileData = file.getFileData();
            InputStream sbs = new ByteArrayInputStream(fileData);
            try {
                DynamicObject dynamic = BusinessDataServiceHelper.loadSingle(sign, "id",new QFilter("billno",QCP.equals,billno).toArray());
                        switch (sign){

                    //标书编制
                   case "src_biddoc":
                       DynamicObject biddoc = BusinessDataServiceHelper.loadSingle(dynamic.getPkValue(), dynamic.getDynamicObjectType().getName());
                       boolean ispaper = biddoc.getBoolean("zmee_ispaper");
                       if(ispaper){
                           DynamicObject publishnotice = BusinessDataServiceHelper.loadSingle("src_publishnotice", "id,",new QFilter("billno",QCP.equals,billno).toArray());
                          // BosUtil.setAttachment(file,publishnotice , attName, "attachmentpanel");
                           BosUtil.setAttachment(sbs,publishnotice , name, "attachmentpanel");
                       }else {
                           BosUtil.setAttachment(sbs,dynamic, name,"zmee_attachmentpanelap");
                       }
                       break;
                   //定标单
                   case "src_decision":
                       BosUtil.setAttachment(sbs,dynamic, name,"attachmentpanel");
                       break;
                   //项目立项
                   case "pmas_pro_approval":
                      BosUtil.setAttachment(sbs,dynamic, name,"zmee_attachmentpanelap1");
                       break;
                   //支出合同
                   case "pmct_outcontract":
                       BosUtil.setAttachment(sbs,dynamic, name,"zmee_contractaccessory");
                       break;
               }
                   logger.info("==上传成功==");
                   apiResult.setMessage("上传成功！");
            }catch (Exception e){
                logger.info("==上传失败==:"+e);
                apiResult.setErrorCode(e.toString());
                apiResult.setMessage("上传失败！");
            }

        }
        return apiResult;
    }


    private static MultipartFile getMulFileByPath(File file, String fieldName) {
        FileItem fileItem = createFileItem(file,fieldName);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }


    private static FileItem createFileItem(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        FileInputStream fis = null;
        OutputStream os = null;
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            fis = new FileInputStream(file);
            os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            logger.info("file转化出错createFileItem(File file, String fieldName)报错"+e);
        }finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                logger.info("file转化出错createFileItem(File file, String fieldName)时io关闭出现错误");
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                logger.info("file转化出错createFileItem(File file, String fieldName)时io关闭出现错误");
            }
        }
        return item;
    }

}
